<?php


namespace app\controller\home;


use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use app\common\controller\BaseController;
use think\App;
use think\Cache;
use think\exception\ValidateException;

class Sms extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * @return array
     * 发送短信
     */
    public function sendMessage()
    {
        //生成随机码
        $key = '';
        $pattern = '1234567890';
        for ($i = 0; $i < 6; $i++) {
            $key .= $pattern[mt_rand(0, 9)];
        }
        try {
//            validate(\app\validate\Sms::class)->check($this->params);
            if (empty($this->params['phone'])) {
                return $this->returnError(-1, [], '手机号码不存在');
            }
            \think\facade\Cache::set("sms:mobile:{$this->params['phone']}",$key,300);
            AlibabaCloud::accessKeyClient(config('sms.accessKeyId')
                , config('sms.accessKeySecret'))
                ->regionId('cn-hangzhou')
                ->asDefaultClient();
            try {
                $result = AlibabaCloud::rpc()
                    ->product('Dysmsapi')
                    // ->scheme('https') // https | http
                    ->version('2017-05-25')
                    ->action('SendSms')
                    ->method('POST')
                    ->host('dysmsapi.aliyuncs.com')
                    ->options([
                        'query' => [
                            'RegionId' => "cn-hangzhou",
                            'PhoneNumbers' => $this->params['phone'],
                            'SignName' => config('sms.signName'),
                            'TemplateCode' => config('sms.templateCode'),
                            'TemplateParam' => "{code:$key}"
                        ],
                    ])
                    ->request();
                return $this->returnRight($result->toArray());
            } catch (ClientException $e) {
                return $this->returnException($e->getErrorMessage());
            } catch (ServerException $e) {
                return $this->returnException($e->getErrorMessage());
            }
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->returnException($e);
        }
    }
}